package com.wjjun.processor;

import com.google.auto.service.AutoService;
import com.squareup.javapoet.JavaFile;
import com.squareup.javapoet.MethodSpec;
import com.squareup.javapoet.TypeSpec;
import com.wjjun.annotation.Print;

import java.io.IOException;
import java.util.HashSet;
import java.util.Set;

import javax.annotation.processing.AbstractProcessor;
import javax.annotation.processing.Filer;
import javax.annotation.processing.ProcessingEnvironment;
import javax.annotation.processing.Processor;
import javax.annotation.processing.RoundEnvironment;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.Element;
import javax.lang.model.element.Modifier;
import javax.lang.model.element.Name;
import javax.lang.model.element.TypeElement;
import javax.tools.Diagnostic;

@AutoService(Processor.class)
public class PoetProcessor extends AbstractProcessor {

    private Filer filer;

    @Override
    public synchronized void init(ProcessingEnvironment processingEnv) {
        super.init(processingEnv);
         filer = processingEnv.getFiler();
    }

    /**
     * 要扫描的注解,返回set集合
     * @return
     */
    @Override
    public Set<String> getSupportedAnnotationTypes() {
        HashSet<String> set = new HashSet<>();
        set.add(Print.class.getCanonicalName());
        return  set;
    }

    @Override
    public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
        if( annotations.isEmpty()){
            return  false;
        }
        //拿到所有添加Print注解的成员变量
        Set<? extends Element> elements = roundEnv.getElementsAnnotatedWith(Print.class);
        //生成类
        TypeSpec.Builder classBuilder = TypeSpec
                .classBuilder("PrintUtil")
                .addModifiers(Modifier.PUBLIC, Modifier.FINAL);

        for (Element element : elements) {
            //拿到成员变量名
            Name simpleName = element.getSimpleName();

            processingEnv.getMessager().printMessage(Diagnostic.Kind.NOTE, "成员变量:"+simpleName.toString());

            //生成方法
            MethodSpec method = MethodSpec.methodBuilder("print"+simpleName.toString().toUpperCase())
                    .addModifiers(Modifier.PUBLIC, Modifier.STATIC)
                    .returns(void.class)
                    .addStatement("$T.out.println($S)", System.class, "Hello, JavaPoet!")
                    .build();
            classBuilder.addMethod(method);
        }
        //包
        JavaFile javaFile = JavaFile
                .builder("com.wjjun.test", classBuilder.build())
                .build();
        try {
            javaFile.writeTo(filer);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 编译版本,固定写法
     * @return
     */
    @Override
    public SourceVersion getSupportedSourceVersion() {
        return processingEnv.getSourceVersion();
    }

}
